package com.yummy.common;

import cn.hutool.core.date.DateUtil;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.yummy.entity.Employee;
import com.yummy.entity.User;
import com.yummy.service.EmployeeService;
import com.yummy.service.UserService;
import org.mybatis.logging.Logger;
import org.mybatis.logging.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Component
public class TokenUtils {

	/**
	 * PlayLoad 中有用户的信息，需要通过Service获取，所以要注入Service
	 */
	@Autowired
	private EmployeeService employeeService;

	@Autowired
	private UserService userService;

	@Autowired
	RedisTemplate redisTemplate;

	private Logger logger = LoggerFactory.getLogger(TokenUtils.class);


	/**
	 * 生成token
	 *
	 * @param userId 用户编号
	 * @return
	 */
	public String getToken(String userId, String password) {
		return JWT.create().withAudience(userId) // 将 user id 保存到 token 里面,作为载荷
				.withExpiresAt(DateUtil.offsetHour(new Date(), 2)) // 2小时后token过期
				.sign(Algorithm.HMAC256(password)); // 以 secretKey + password 作为 token 的密钥 secret
	}

	/**
	 * 获取当前登录的用户信息
	 *
	 * @return employee对象
	 */
	public Employee getCurrentEmp(HttpServletRequest request) {
		try {
//            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
			String token = request.getHeader("Authorization");

			//-- StrUtil HuTool中关于String的工具方法！
			if (StrUtil.isNotBlank(token)) {
				String userId = JWT.decode(token).getAudience().get(0);
				return employeeService.findEmpById(userId);
			}
		} catch (Exception e) {
			return null;
		}
		return null;
	}

	public User getCurrentUser(HttpServletRequest request){

		try{
			String token = request.getHeader("Authorization");
			if(StrUtil.isNotBlank(token)) {
				String userId =JWT.decode(token).getAudience().get(0);
				return userService.findUserById(userId);
			}
		}catch(Exception e){
			return null;
		}
		return null;
	}


	public Integer getCurrentStore(HttpServletRequest request) {

//            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
			Employee currentEmp = getCurrentEmp(request);

			//-- StrUtil HuTool中关于String的工具方法！


			return currentEmp.getStoreId();


	}
}